﻿using NB.MGJ.Common.Cache;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace NB.MGJ.Common.MVC
{
    public class BaseController : Controller
    {
        /// <summary>
        ///用登录用户IP 
        /// </summary>
        protected string UserIp
        {
            get
            {

                string userIP = string.Empty;

                try
                {
                    if (System.Web.HttpContext.Current == null
                     || System.Web.HttpContext.Current.Request == null
                     || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    {
                        return "";
                    }

                    string CustomerIP = "";

                    CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                    if (!string.IsNullOrEmpty(CustomerIP))
                    {
                        return CustomerIP;
                    }

                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                    if (!String.IsNullOrEmpty(CustomerIP))
                    {
                        return CustomerIP;
                    }

                    if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    {
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                        if (CustomerIP == null)
                        {
                            CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                        }
                    }
                    else
                    {
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }

                    if (string.Compare(CustomerIP, "unknown", true) == 0 || String.IsNullOrEmpty(CustomerIP))
                    {
                        return System.Web.HttpContext.Current.Request.UserHostAddress;
                    }
                    return CustomerIP;
                }
                catch { }

                return userIP;
            }
        }

        /// <summary>
        /// 系统异常
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {
            LogHelper.Add("异常", "系统异常", filterContext.Exception.Message, UserIp, LogOnUser);
            //base.OnException(filterContext);
        }

        #region 登陆信息
        /// <summary>
        /// 返回登陆者信息
        /// </summary>
        public  LogOnUserModel LogOnUser
        {
            get
            {
                return SessionHelper.LogOnUser<LogOnUserModel>();
            } 
        }

        #endregion

        #region ViewResult
        /// <summary>
        /// Creates a System.Web.Mvc.ViewResult object that renders a view to the response.
        /// </summary>
        /// <returns>The view result that renders a view to the response.</returns>
        public ViewResult TView()
        {
            return View();
        }

        /// <summary>
        /// Creates a System.Web.Mvc.ViewResult object by using the model that renders
        //     a view to the response.
        /// </summary>
        /// <param name="model">The model that is rendered by the view.</param>
        /// <returns>The view result.</returns>
        public ViewResult TView(object model)
        {
            return View(model);
        }

        #endregion 

        #region JsonResult
        public ActionResult Json(ModelStateDictionary modelState)
        {
            var keys = modelState.Keys;
            var diction = new Dictionary<string, string>();
            foreach (var item in keys)
            {
                if (modelState[item].Errors.Count == 0) continue;
                if (!string.IsNullOrEmpty(item))
                {
                    diction.Add(item, modelState[item].Errors[0].ErrorMessage);
                }
            }
            return Json(new JsonError("modelstate", diction));
        }

        //public ActionResult JsonUserException(string message, params object[] parameters)
        //{
        //    return new UserExceptionResult(message, parameters);
        //}
        #endregion

        #region 其他
        //public ActionResult UserException(string messageId, params object[] parameters)
        //{
        //    return new UserExceptionResult(messageId, parameters);
        //}

        public string GetClientIP()
        {
            string ip;
            if (Request.ServerVariables["HTTP_VIA"] != null)
            {
                ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                ip = Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return ip;
        }
        #endregion

        #region 序列化
        public string ToJsonString(object obj)
        {
            return new JavaScriptSerializer().Serialize(obj);
        }
        /// <summary>
        /// 序列号DataTable
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string Serialize(DataTable dt)
        {
            if (dt == null)
            {
                return "-1";
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                list.Add(result);
            }
            return serializer.Serialize(list);
        }
        #endregion


        #region 判断session是否失效

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            LogOnUserModel user = SessionHelper.LogOnUser<LogOnUserModel>();
            if (user == null) //检查用户是否有登录
            {
                var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                if (controllerName == "Mobile")
                {

                    var parm = filterContext.ActionParameters;
                    ContentResult r = new ContentResult();
                    //r.Content = " <script> if(confirm('登录超时，是否重新登录？')){window.location = '/MobileHome/LoginIndex';} </script>";
                    r.Content = " <script>window.location = '/MobileHome/LoginIndex?batchId="+parm["batchId"]+"';</script>";
                    filterContext.Result = r;
                }
                else
                {
                    ContentResult r = new ContentResult();
                    r.Content = " <script> if(confirm('登录超时，是否重新登录？')){window.parent.parent.parent.location = '/Home/Index';} </script>";
                    filterContext.Result = r;
                }
            }
        }
        #endregion
    }
}
